"""
文件处理API - 处理Word和PDF文件提取文本
"""

from fastapi import APIRouter, UploadFile, File, HTTPException
from typing import Optional
import io
import logging
import asyncio
from concurrent.futures import ThreadPoolExecutor

# 提前导入文档处理库
try:
    from docx import Document
    DOCX_AVAILABLE = True
except ImportError:
    DOCX_AVAILABLE = False

try:
    import PyPDF2
    PDF_AVAILABLE = True
except ImportError:
    PDF_AVAILABLE = False

router = APIRouter(prefix="/api/v1/files", tags=["files"])
logger = logging.getLogger(__name__)

# 创建线程池用于处理CPU密集型任务
executor = ThreadPoolExecutor(max_workers=3)


@router.post("/extract-text")
async def extract_text_from_file(
    file: UploadFile = File(...)
):
    """
    从上传的文件中提取文本内容
    支持: txt, docx (新版Word), pdf
    注意: 不支持旧版 .doc 格式
    """
    try:
        # 获取文件扩展名
        filename = file.filename.lower()

        if filename.endswith('.txt'):
            # 处理TXT文件
            content = await file.read()
            text = content.decode('utf-8', errors='ignore')
            return {
                "success": True,
                "data": {
                    "text": text,
                    "filename": file.filename,
                    "type": "txt"
                }
            }

        elif filename.endswith('.doc'):
            # 旧版Word格式不支持
            raise HTTPException(
                status_code=400,
                detail="不支持旧版Word格式(.doc)，请将文件另存为.docx格式后重试"
            )

        elif filename.endswith('.docx'):
            # 处理DOCX文件
            if not DOCX_AVAILABLE:
                raise HTTPException(
                    status_code=500,
                    detail="服务器未安装python-docx库，无法处理Word文件"
                )

            try:
                content = await file.read()

                # 在线程池中处理文档解析（避免阻塞事件循环）
                def extract_docx_text(file_content):
                    doc = Document(io.BytesIO(file_content))
                    paragraphs = [para.text for para in doc.paragraphs if para.text.strip()]
                    return '\n\n'.join(paragraphs)

                loop = asyncio.get_event_loop()
                text = await loop.run_in_executor(executor, extract_docx_text, content)

                return {
                    "success": True,
                    "data": {
                        "text": text,
                        "filename": file.filename,
                        "type": "docx"
                    }
                }
            except Exception as e:
                logger.error(f"Word文件处理失败: {str(e)}")
                raise HTTPException(
                    status_code=500,
                    detail=f"Word文件处理失败: {str(e)}"
                )

        elif filename.endswith('.pdf'):
            # 处理PDF文件
            if not PDF_AVAILABLE:
                raise HTTPException(
                    status_code=500,
                    detail="服务器未安装PyPDF2库，无法处理PDF文件"
                )

            try:
                content = await file.read()

                # 在线程池中处理PDF解析（避免阻塞事件循环）
                def extract_pdf_text(file_content):
                    pdf_reader = PyPDF2.PdfReader(io.BytesIO(file_content))
                    text_parts = []
                    for page in pdf_reader.pages:
                        text_parts.append(page.extract_text())
                    return '\n\n'.join(text_parts), len(pdf_reader.pages)

                loop = asyncio.get_event_loop()
                text, page_count = await loop.run_in_executor(executor, extract_pdf_text, content)

                return {
                    "success": True,
                    "data": {
                        "text": text,
                        "filename": file.filename,
                        "type": "pdf",
                        "pages": page_count
                    }
                }
            except Exception as e:
                logger.error(f"PDF文件处理失败: {str(e)}")
                raise HTTPException(
                    status_code=500,
                    detail=f"PDF文件处理失败: {str(e)}"
                )
        else:
            raise HTTPException(
                status_code=400,
                detail=f"不支持的文件类型。仅支持 .txt, .docx, .pdf"
            )

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"文件处理失败: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"文件处理失败: {str(e)}"
        )
